from pydantic import BaseModel, Field, field_validator, conint
from typing import List

from pydantic_core.core_schema import ValidationInfo

from enums.modbus_funcode import ModbusFunctionCode
from enums.modbus_register import RegisterType, InnerDecode


# 基础模型（复用公共字段）
class DeviceBase(BaseModel):
    device_name: str = Field(..., min_length=1, description="设备名称不能为空")
    slave_id: int = Field(..., ge=0, le=255, description="从站ID范围0-255")


# 1. 从站基础信息
class Slave(DeviceBase):
    pass  # 直接继承所有字段


# 2. 从站名称列表
class SlaveIdList(BaseModel):
    device_name: str = Field(..., min_length=1)


# 3. 从站地址范围
class SlaveAddress(DeviceBase):
    register_type: RegisterType = Field(..., description="寄存器类型枚举")
    start_address: int = Field(..., ge=0, le=65535, description="起始地址范围0-65535")
    end_address: int = Field(..., ge=0, le=65535, description="结束地址范围0-65535")

    # 验证地址范围有效性
    @field_validator('end_address')
    def check_address_range(cls, v: int, values: ValidationInfo):
        if 'start_address' in values.data and v < values.data['start_address']:
            raise ValueError('结束地址必须大于等于起始地址')
        return v


# 4. 从站详细信息
class SlaveInfo(DeviceBase):
    register_type: RegisterType = Field(..., description="寄存器类型枚举")


# 5. 写寄存器模型
class WriteRegister(DeviceBase):
    register_type: RegisterType = Field(..., description="寄存器类型枚举")
    start_address: int = Field(..., ge=0, le=65535, description="起始地址范围0-65535")
    data_type: InnerDecode = Field(..., description="数据解码类型枚举")
    value_list: List[int] = Field(..., description="写入值列表")
    write_func: ModbusFunctionCode = Field(..., description="Modbus功能码枚举")
